package models

import (
	"github.com/astaxie/beego/orm"
	"shopping/helper"
)

type Item struct {
	Id      int
	Pid     int
	Uid     int
	Oid     int
	Remarks string
	Flag    int
	//Product   *Product //状态 `orm:fk`
}

/*
type Items struct{
  Itemid   int
  Uid      int
  Pname    string
  Num      int
  Iremarks string
  Premarks string
}*/

//新增item，如果pid，uid，flag=0则更新
func (i *Item) Additem(pid int, uid int, num int) (string) {

	o := orm.NewOrm()
	//beego.Debug("Additem", "76")
	var item Item

	err := o.QueryTable("Item").Filter("pid", pid).Filter("uid", uid).Filter("flag", int(0)).One(&item)
	if err == orm.ErrMultiRows {
		// 多条的时候报错
		return "multiRow-models.Item"
	}

	if err == orm.ErrNoRows {
		// 没有找到记录
		item.Pid = pid
		item.Remarks = "无"
		item.Flag = int(0)
		item.Uid = uid
		item.Oid = int(0)
		id, ierr := o.Insert(&item)
		if ierr == nil {
			var itns Itemnum
			itnid, itnerr := itns.Additem(int(id), num)
			if itnerr == nil {
				return helper.I64ts(id) + "添加成功" + helper.I64ts(itnid)
			}
			return "数据插入错误"
		}
		return "数据插入错误"

	}
	/*这个方法增加不起作用。。
	  num, err := o.QueryTable("Itemnum").Filter("itemid",item.Id).Update(orm.Params{
		"num": o.ColValue(o.Col_Add, num),
	})*/

	res, errrow := o.Raw("UPDATE Itemnum SET num = num + ? WHERE Itemid = ?", num, item.Id).Exec()
	//  res, err := o.Raw("UPDATE user SET name = ?", "your").Exec()
	if errrow == nil {
		num, _ := res.RowsAffected()
		return helper.I64ts(num) + "更新成功"
	}

	return "更新失败"
}

func (n *Item) Deleteitem(itid int) (string) {
	o := orm.NewOrm()
	res, errrow := o.Raw("UPDATE Item SET flag = ? WHERE Id = ?", 1, itid).Exec()
	//  res, err := o.Raw("UPDATE user SET name = ?", "your").Exec()
	if errrow == nil {
		num, _ := res.RowsAffected()
		return helper.I64ts(num) + "更新成功"
	}
	return "更新失败"

}
